package org.zlb.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.zhiqim.kernel.extend.SS;
import org.zhiqim.kernel.util.Images;
import org.zhiqim.kernel.util.Randoms;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Streams;
import org.zhiqim.kernel.util.codes.RSA;
import org.zlb.manager.entity.FunAvatar;
import org.zlb.manager.entity.FunParam;
import org.zlb.manager.entity.OrgDept;
import org.zlb.manager.entity.OrgOperator;
import org.zlb.manager.service.FunAvatarService;
import org.zlb.manager.service.FunParamService;
import org.zlb.manager.service.OrgDeptService;
import org.zlb.manager.service.OrgOperatorService;

import java.sql.Timestamp;

import static org.zhiqim.kernel.constants.SignConstants.ID13;
import static org.zlb.manager.Constant.*;

/**
 * TODO
 *
 * @author zhoulingbo
 * @date 2021/8/18 15:15
 */
@Component
public class InitAfter implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(InitAfter.class);

    @Autowired
    private FunAvatarService avatarService;

    @Autowired
    private FunParamService paramService;

    @Autowired
    private OrgOperatorService operatorService;

    @Autowired
    private OrgDeptService deptService;

    @Autowired
    private Passworder passworder;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        initParam();
        initAvatar();
        initDept();
        initOperator();
    }

    /** 初始化参数 */
    private void initParam() throws Exception
    {
        if (paramService.count() > 0)
            return;

        SS keys = RSA.buildKeyPair();

        FunParam param = new FunParam();
        param.setParamGroup(ZLB_NAME);
        param.setParamKey(PUBLIC_KEY);
        param.setParamValue(keys.key());
        param.setParamSeq(10);
        param.setParamType((byte) 1);
        param.setParamValidate(null);
        param.setParamDesc("随机生成的公钥");

        paramService.save(param);

        param = new FunParam();
        param.setParamGroup(ZLB_NAME);
        param.setParamKey(PRIVATE_KEY);
        param.setParamValue(keys.value());
        param.setParamSeq(11);
        param.setParamType((byte) 1);
        param.setParamValidate(null);
        param.setParamDesc("随机生成的私钥");

        paramService.save(param);

        logger.info("初始化参数完成!");
    }

    /** 初始化头像 */
    private void initAvatar() throws Exception
    {
        if (avatarService.count() > 0)
            return;

        long avatarId = ID13;
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("static/avatar/*.jpg");
        for (Resource resource : resources)
        {
            byte[] data = Streams.getBytesFilePath(resource.getFile().getAbsoluteFile());
            byte[]  bytes50 = Images.resizePNG(data, 50, 50);
            byte[]  bytes100 = Images.resizePNG(data, 100, 100);
            byte[]  bytes150 = Images.resizePNG(data, 150, 150);

            FunAvatar avatar = new FunAvatar();
            avatar.setAvatarId(avatarId++);
            avatar.setAvatarType((byte) 0);
            avatar.setAvatarTime(System.currentTimeMillis());
            avatar.setAvatar50(bytes50);
            avatar.setAvatar100(bytes100);
            avatar.setAvatar150(bytes150);

            avatarService.save(avatar);
        }

        logger.info("初始化头像完成!");
    }

    /** 初始化部门 */
    private void initDept() throws Exception
    {
        if (deptService.count() > 0)
            return;

        OrgDept dept = new OrgDept();
        dept.setParentId(0);
        dept.setDeptId(ID13);
        dept.setDeptName("湘水余波");
        dept.setDeptStatus((byte) 0);
        dept.setDeptLevel(0);
        dept.setDeptParentAll("0");

        deptService.save(dept);
        logger.info("初始化部门完成!");
    }

    /** 初始操作员，使用操作员独立数据库 */
    private void initOperator() throws Exception
    {
        if (operatorService.count() > 0)
            return;

        Timestamp timestamp = Sqls.nowTimestamp();
        String passSalt = Randoms.lettersDigitsSecure(64);

        OrgOperator operator = new OrgOperator();
        operator.setOperatorCode("admin");
        operator.setOperatorPass(passworder.encode(ADMIN, PASSWORD, passSalt));
        operator.setOperatorPassSalt(passSalt);
        operator.setOperatorStatus((byte) 0);
        operator.setOperatorType((byte) 0);
        operator.setOperatorAvatar(ID13);
        operator.setOperatorName("超级管理员");
        operator.setOperatorCreated(timestamp);
        operator.setOperatorModified(timestamp);

        operatorService.save(operator);
        logger.info("初始化操作员完成!");
    }
}
